package com.yanqu.road.queue;

import com.alibaba.fastjson.JSONArray;
import com.yanqu.road.server.manger.DataUploadInfoMgr;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @author duli
 * @version 1.0
 * @date 2020/9/9 10:56
 * @Description 日志分析队列
 */
public class LogAnalysisPushQueue {
    private final static Logger log = LogManager.getLogger(LogAnalysisPushQueue.class.getName());

    // 消息队列
    private static Queue<Object> msgQueue = new LinkedList<Object>();


    private static final int maxSize = 50001;

    public static void add(Object msg) {
        if (!DataUploadInfoMgr.isAllowUpload()) {
            return;
        }
        synchronized (msgQueue) {
            msgQueue.add(msg);
            checkQueue();
        }
    }

    public static void checkQueue() {
        int queueSize = msgQueue.size();
        if (queueSize >= maxSize) {
            JSONArray jsonArray = poll(queueSize - maxSize);
            log.warn("LogAnalysisPushQueue size exceeded,over size:{}", queueSize - maxSize);
        }

    }

    public static JSONArray poll(int max_num) {
        JSONArray jsonArray = new JSONArray();
        synchronized (msgQueue) {
            for (int i = 0; i < max_num; i++) {
                Object data = msgQueue.poll();
                if (data == null) {
                    break;
                }
                jsonArray.add(data);
            }
            return jsonArray;
        }
    }
}
